<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use Exception;
use think\Db;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800008 extends BasePay{

    const APP_KEY = '960085BAE1EA4D651D27AC35C2289673';

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function uinfo(){
        $params = Request::instance()->param();
        //查看币种是否充足

        $data = [
            "uid" => $params['uid'],
            "gameId" => 800008,
            "relateId" => $params['relateId'],
        ];
        $sign = md5($data['gameId'].$data['relateId'].self::APP_KEY.$data['uid']);

        $response = $this->curl('https://m.api.aboveok.com/game/uinfo?token='.$params['token'].'&sign='.$sign, $data);
        exit($response);
    }

    public function order()
    {
        parent::order();
        $params = Request::instance()->param();
        
        try{
            $json_string = file_get_contents(env('PLATFORM.USD'));

            $config = json_decode($json_string, true);
            $usd  = $config[$this->order_array['goods_id']];
            if(empty($usd)){
                mylog('计费点对应的美元金额找不到');
                throw new \Exception('计费点对应的美元金额找不到');
            }

            $coin = (int)ceil($usd['Mpay'])*1000;
            $data = [
                "uid" => $params['uid'],
                "orderId" => $this->order_array['id'],
                "gameId" => 800008,
                "coin" => $coin,
                "type" => 1,
            ];
            $sign = md5($data['orderId'].$data['gameId'].$data['coin'].$data['type'].self::APP_KEY.$data['uid']);
            $response = $this->curl('https://m.api.aboveok.com/game/updcoin?token='.$params['token'].'&sign='.$sign, $data);

            $res = json_decode($response,true);
            //余额不足 需要特殊返回码给客户端做后续操作
            if($res['errorCode'] == 106002 ){
                exit(json_encode(['code'=>106002]));
            }

            
            //成功 直接发货
            if($res['errorCode'] != 0){
                throw new \Exception('返回码异常');
            }
            //验证签名
            if($res['data']['sign'] != md5($this->order_array['id'].self::APP_KEY)){
                throw new \Exception('返回签名验证失败');
            }
           
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$this->order_array['id']])->find();
             //保存数据
             $tradeLog->dollPrice = $coin;
             $tradeLog->dollPriceType = '直播币';
             $tradeLog->save();
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            exit(json_encode(['code'=>200]));
        }catch (\Exception $exception){
            mylog('800008-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return exit(json_encode(['code'=>-1]));
        }

    }



    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HTTPHEADER,[]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        
        curl_close($ch);
        mylog($response);
        return $response;

        
    }

   
}
